package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.databinding.ActivityPicManageBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PicManageActivity extends BaseAc<ActivityPicManageBinding> {

    private SelVideoAdapter pictureAdapter;
    private List<SelectMediaEntity> listDelete = new ArrayList<>();
    private Dialog myDeleteDialog;
    private boolean isEdit = false;


    @Override
    protected int onCreate() {
        return R.layout.activity_pic_manage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivPicManageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        //相册图片
        pictureAdapter = new SelVideoAdapter();
        pictureAdapter.setEdit(isEdit);
        mDataBinding.rvPicList.setLayoutManager(new GridLayoutManager(mContext, 3));
        mDataBinding.rvPicList.setAdapter(pictureAdapter);
        pictureAdapter.setOnItemClickListener(this);

        mDataBinding.ivPicManage.setOnClickListener(this);
        mDataBinding.ivManageCancel.setOnClickListener(this);
        mDataBinding.ivManageDelete.setOnClickListener(this);
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPicManage:
                isEdit = true;
                pictureAdapter.setEdit(isEdit);
                pictureAdapter.notifyDataSetChanged();
                mDataBinding.ivPicManage.setVisibility(View.GONE);
                mDataBinding.llManage.setVisibility(View.VISIBLE);
                break;
            case R.id.ivManageCancel://取消
                isEdit = false;
                pictureAdapter.setEdit(isEdit);
                getData();
                listDelete.clear();
                mDataBinding.ivPicManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivManageDelete://删除
                if (listDelete.size() == 0) {
                    return;
                }
                myDeleteDialog.show();
                break;
            //删除弹框
            case R.id.ivDialogDeleteConfirm:
                for (int i = 0; i < listDelete.size(); i++) {
                    //从此文件夹删除
                    mContext.getContentResolver().delete(Uri.parse(listDelete.get(i).getUri()), null, null);
                }
                listDelete.clear();
                isEdit = false;
                pictureAdapter.setEdit(isEdit);
                getData();
                myDeleteDialog.dismiss();
                ToastUtils.showShort(getString(R.string.delete_suc));
                mDataBinding.ivPicManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (pictureAdapter.getItem(position).isChecked()) {
                pictureAdapter.getItem(position).setChecked(false);
                listDelete.remove(pictureAdapter.getItem(position));
                pictureAdapter.notifyDataSetChanged();
            } else {
                listDelete.add(pictureAdapter.getItem(position));
                pictureAdapter.getItem(position).setChecked(true);
                pictureAdapter.notifyDataSetChanged();
            }
        } else {
            ImgDetailActivity.imgPath = pictureAdapter.getItem(position).getPath();
            startActivity(ImgDetailActivity.class);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        mDataBinding.rvPicList.setVisibility(View.GONE);
                        mDataBinding.ivPicManageNoData.setVisibility(View.VISIBLE);
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    pictureAdapter.setList(selectMediaEntities);
                    mDataBinding.rvPicList.setVisibility(View.VISIBLE);
                    mDataBinding.ivPicManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvPicList.setVisibility(View.GONE);
                    mDataBinding.ivPicManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

}